package site.beanyon.now.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.beanyon.now.mapper.AnalysisMapper;
import site.beanyon.now.model.dto.ActivityDTO;
import site.beanyon.now.model.dto.TimeCardDTO;
import site.beanyon.now.model.dto.TimeSpanDTO;
import site.beanyon.now.model.po.TimeCardPO;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据分析服务
 */
@Service
public class AnalysisServiceImpl implements AnalysisService {
    @Autowired
    private AnalysisMapper analysisMapper;

    @Autowired
    private TimeCardService timeCardService;

    @Autowired
    private UserService userService;

    /**
     * 获取某用户的所有时间卡片列表
     *
     * @return 时间卡片列表
     */
    @Override
    public List<TimeCardDTO> getAllData() {
        Integer userId = this.userService.getCurrentUser().getId();
        List<TimeCardPO> timeCardPOList = this.analysisMapper.listAllTimeCard(userId);
        return timeCardService.convertPOs2DTOs(timeCardPOList);
    }

    /**
     * 获取给定时间范围内的时间卡片列表
     *
     * @param startDate 起始时间
     * @param endDate   终止时间
     * @return 时间卡片列表
     */
    @Override
    public List<TimeCardDTO> getAllData(String startDate, String endDate) {
        Integer userId = this.userService.getCurrentUser().getId();
        List<TimeCardPO> timeCardPOList = this.analysisMapper.listTimeCard(userId, startDate, endDate);
        return timeCardService.convertPOs2DTOs(timeCardPOList);
    }

    /**
     * 获取当前用户的所有activity及对应耗时，以及总耗时数据
     *
     * @return 用户总耗时及activity列表
     */
    @Override
    public Map<String, Object> listAllActivity() {
        // 从数据库中查询时间卡片列表
        List<TimeCardDTO> timeCardPOList = this.getAllData();

        // 最终返回的活动列表
        List<ActivityDTO> activityDTOList = new ArrayList<>();

        // 用于中间构造活动列表的Map
        Map<String, ActivityDTO> activityMap = new HashMap<>(16);

        // 全部活动的总时间，单位为分钟
        long totalMinuteSum = 0L;

        // 根据时间卡片构造活动Map
        for (TimeCardDTO timeCardDTO : timeCardPOList) {
            // 当前时间卡片的活动名称
            String activity = timeCardDTO.getActivity();

            //当前时间卡片的耗时
            long currentTimeCardMinuteSum = 0L;

            List<TimeSpanDTO> timeSpanList = timeCardDTO.getTimeSpanList();

            // 统计当前时间卡片的耗时
            for (TimeSpanDTO timeSpanDTO : timeSpanList) {
                long spentTime = (timeSpanDTO.getEndTime() - timeSpanDTO.getStartTime()) / 1000 / 60;
                if (spentTime < 0) {
                    continue;
                }
                currentTimeCardMinuteSum += spentTime;
                totalMinuteSum += spentTime;
            }

            ActivityDTO activityDTO = activityMap.get(activity);
            if (activityDTO == null) {
                activityMap.put(activity, new ActivityDTO(activity, currentTimeCardMinuteSum));
            } else {
                activityDTO.setSpentTimeMinutes(activityDTO.getSpentTimeMinutes() + currentTimeCardMinuteSum);
            }
        }

        // 将Activity 的Map转为List，并为每个Activity计算ratio
        for (Map.Entry<String, ActivityDTO> activityEntry : activityMap.entrySet()) {
            ActivityDTO activityDTO = activityEntry.getValue();
            DecimalFormat df = new DecimalFormat("0.00");
            double ratioNum = activityDTO.getSpentTimeMinutes() * 1.0 / totalMinuteSum * 100;
            String formatedRatioNum = df.format(ratioNum);
            activityDTO.setRatio(formatedRatioNum + "%");
            activityDTOList.add(activityDTO);
        }

        // 按照耗时分钟数进行排序
        activityDTOList.sort((o1, o2) -> {
            if (o1.getSpentTimeMinutes() < o2.getSpentTimeMinutes()) {
                return 1;
            } else {
                return -1;
            }
        });

        Map<String, Object> result = new HashMap<>(16);
        result.put("totalMinuteSum", totalMinuteSum);
        result.put("activityList", activityDTOList);
        return result;
    }
}
